<template>
  <div class="query-form">
    <el-form
      :model="queryForm"
      ref="queryFormRef"
      label-width="100px"
      :inline="true"
    >
       <el-form-item label="客户ID">
        <el-input v-model="queryForm.clientPartyId" placeholder="双击选择客户" @dblclick="clientDialogVisible = true" style="width: 200px" />
      </el-form-item>

      <el-form-item label="客户名称">
        <el-input v-model="queryForm.clientName" placeholder="请输入客户名称" style="width: 200px" />
      </el-form-item>

      <el-form-item label="商品信息">
        <el-input v-model="queryForm.goodsDesc" placeholder="请输入商品名称或商品编码" style="width: 260px" />
      </el-form-item>

      <el-form-item label="销售部门">
        <el-select v-model="queryForm.saleOrg" placeholder="请选择销售部门" style="width: 200px">
          <el-option label="100上药湖南" value="100" />
          <el-option label="301销售一部" value="301" />
          <el-option label="302销售二部" value="302" />
          <el-option label="303销售三部" value="303" />
          <el-option label="304销售四部" value="304" />
          <el-option label="305销售五部" value="305" />
          <el-option label="306销售六部" value="306" />
          <el-option label="307分子公司" value="307" />
          <el-option label="308销售八部" value="308" />
          <el-option label="309销售九部" value="309" />
          <el-option label="310销售十部" value="310" />
          <el-option label="311销售十一部" value="311" />
          <el-option label="312销售十二部" value="312" />
          <el-option label="313带量采购" value="313" />
          <el-option label="314销售十四部" value="314" />
          <el-option label="315销售十五部" value="315" />
          <el-option label="316销售十六部" value="316" />
        </el-select>
      </el-form-item>

      <el-form-item label="订单类型">
        <el-select v-model="queryForm.orderType" placeholder="请选择" style="width: 200px">
          <el-option label="全部" value="" />
          <el-option label="正常订单" value="1" />
          <el-option label="金额修正订单" value="2" />
          <el-option label="退货订单" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="单据状态">
        <el-select v-model="queryForm.opFlagName" placeholder="请选择" style="width: 200px">
          <el-option label="全部" value="" />
          <el-option label="新增" value="新增" />
          <el-option label="已确认" value="已确认" />
          <el-option label="作废" value="作废" />
        </el-select>
      </el-form-item>

      <el-form-item label="是否截止">
        <el-select v-model="queryForm.isEnd" placeholder="请选择" style="width: 200px">
          <el-option label="全部" value="" />
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="开票员">
        <el-input v-model="queryForm.createrName" placeholder="请输入开票员" style="width: 200px" />
      </el-form-item>

      <el-form-item label="采购员">
        <el-input v-model="queryForm.buyerName" placeholder="请输入采购员" style="width: 200px" />
      </el-form-item>

      <el-form-item label="批号信息">
        <el-input v-model="queryForm.lotNo" placeholder="请输入批号信息" style="width: 200px" />
      </el-form-item>

      <el-form-item label="联动日期">
        <el-date-picker
          v-model="currentDate"
          type="daterange"
          range-separator="-"
          start-placeholder="起始时间"
          end-placeholder="结束时间"
          style="width: 300px"
        />
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">清除</el-button>
        <el-button type="success" @click="handleBatchSave">确权</el-button>
      </el-form-item>
      <el-form-item label="合计可补金额">
        <el-input v-model="queryForm.actRebAmtTotal" placeholder="请勾选数据" style="width: 160px" />
      </el-form-item>
      <el-form-item label="合计应收金额">
        <el-input v-model="queryForm.rebAmtTotal" placeholder="请勾选数据" style="width: 160px" />
      </el-form-item>
    </el-form>

     <!-- 弹窗查询客户 -->
    <el-dialog title="选择客户" v-model="clientDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="clientQuery"
            placeholder="请输入客户名称"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="clientSearch">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="dataClient.list"
        style="width: 100%;"
        @row-click="selectClient">
        <el-table-column prop="comPartyId" label="客户ID" width="120" />
        <el-table-column prop="partyOpcode" label="客户代码" />
        <el-table-column prop="partyName" label="客户名称" />
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="dataClient.pageNum"
          v-model:page-size="dataClient.pageSize"
          :total="dataClient.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="clientSearch"
          @current-change="clientSearch"
        />
      </div>
    </el-dialog>
  </div>
  <div class="table-container">
    <el-table
      :data="tableDataList.list"
      border
      style="width: 100%"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      @selection-change="handleSelectionChange"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="clientPartyId" label="客户ID" width="100" />
        <el-table-column prop="clientPartyName" label="客户名称" width="180" />
        <el-table-column prop="sscOrderLinesLotsId" label="供应商代码" width="100" />
        <el-table-column prop="venderName" label="供应商名称" width="180" />
        <el-table-column prop="saleOrg" label="销售部门" width="100" />
        <el-table-column prop="buyerName" label="采购员" width="80" />
        <el-table-column prop="comGoodsId" label="商品ID" width="80" />
        <el-table-column prop="goodsOpcode" label="商品编码" width="100" />
        <el-table-column prop="goodsName" label="商品名称" width="100" />
        <el-table-column prop="goodsDesc" label="商品规格" width="120" />
        <el-table-column prop="unitName" label="单位" width="60" />
        <el-table-column prop="qty" label="数量" width="60" />
        <el-table-column prop="taxPrice" label="含税进价" width="80" />
        <el-table-column prop="purPrice" label="进价" width="100" />
        <el-table-column prop="taxRate" label="税率" width="100" />
        <el-table-column prop="rebAmt" label="应收金额" width="100" />
        <el-table-column label="可补金额" width="120">
          <template #default="scope">
            <el-input
              v-model="scope.row.actRebAmt"
              size="small"
            />
          </template>
        </el-table-column>
        <el-table-column prop="lotNo" label="批号" width="110" />
        <el-table-column
          prop="produceDate"
          label="生产日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column
          prop="expireDate"
          label="有效期"
          width="100"
          :formatter="formatDate"
        /><el-table-column
          prop="impDate"
          label="生成日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column prop="comGoodsBatchId" label="批次号" width="100" />

        <el-table-column prop="productLocation" label="生产厂家" width="200" />
        <el-table-column prop="channelOpcode" label="渠道号" width="100" />
        <el-table-column prop="chcanelName" label="渠道商" width="90" />
        <el-table-column prop="hnyyPurRebateListId" label="政策ID" width="90" />
        <el-table-column prop="checkerName" label="确权人" width="90" />
        <el-table-column
          prop="checkDate"
          label="确权时间"
          width="100"
          :formatter="formatDate"
        />

        <el-table-column prop="opFlagName" label="单据状态" width="120" />
    </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="tableDataList.pageNum"
          v-model:page-size="tableDataList.pageSize"
          :total="tableDataList.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleQuery"
          @current-change="handleQuery"
        />
      </div>

  </div>
</template>

<script setup>
import { reactive, ref,nextTick } from 'vue'
import request from '@/utils/request'
import { ElLoading,ElMessage  } from 'element-plus';
import {currentDate} from '../../utils/time.js';
import dayjs from 'dayjs'

const queryFormRef = ref()
// 查询参数
const queryForm = reactive({
  clientPartyId: '',
  goodsDesc: '', // 商品信息
  sscOrderId: '',
  saleOrg: '',
  sysOrderTypeId: '', // 订单类型
  opFlag: '', // 登记情况
  isEnd: '', // 是否截止
  createrName: '', // 开票员
  buyerName: '',// 采购员
  lotNo: '',
  opFlagName: '', // 单据状态
  startDate: currentDate.value[0],
  endDate: currentDate.value[1],
  pageNum: 1,
  pageSize: 20,
  total: 0,
  actRebAmtTotal:0, // 可补金额合计
  rebAmtTotal:0, // 应收金额合计
  key:1 // 判断是否是确权页面
})


const selectedRows = ref([]) // 存储勾选的行
const handleSelectionChange = (val) => {
  selectedRows.value = val
  // 计算合计
  let actTotal = 0
  let rebTotal = 0

  val.forEach(item => {
    actTotal += Number(item.actRebAmt) || 0
    rebTotal += Number(item.rebAmt) || 0
  })

  // 保留两位
  queryForm.actRebAmtTotal = Number(actTotal.toFixed(2))
  queryForm.rebAmtTotal = Number(rebTotal.toFixed(2))
}
const handleReset=()=>{
  Object.keys(queryForm).forEach(key=>{
      queryForm[key]=''

  })
  queryForm.startDate = dayjs(currentDate.value[0]).format('YYYY-MM-DD')
  queryForm.endDate = dayjs(currentDate.value[1]).format('YYYY-MM-DD')
  queryForm.pageNum=1
  queryForm.pageSize=20
  queryForm.total=0
}

// 数据
const dataClient = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})

// 查询列表数据
const tableDataList = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  list:[]
})

// 日期格式化
const formatDate = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

// 客户弹窗
const clientDialogVisible = ref(false)
const clientQuery = ref('')
const handleQuery = () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '数据加载中，请稍候...',
    background: 'rgba(255, 255, 255, 0.7)',
  });
  console.log('queryForm',queryForm)
  queryForm.startDate = dayjs(currentDate.value[0]).format('YYYY-MM-DD')
  queryForm.endDate = dayjs(currentDate.value[1]).format('YYYY-MM-DD')
  request.post('/account/getData', queryForm).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      tableDataList.list = res.data.list.map(item => {
        return {
          ...item,
          actRebAmt: item.actRebAmt == null || item.actRebAmt === '' ? item.rebAmt : item.actRebAmt
        }
      })
      tableDataList.total = res.data.total
      tableDataList.pageNum = res.data.pageNum
      tableDataList.pageSize = res.data.pageSize
    }

  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    }).finally(() => {
      loadingInstance.close();
    });
}
let loadingInstance = null;
// 客户查询
const clientSearch = () => {
  if (!clientQuery.value) return ElMessage.warning('请输入客户名称')
  nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body',
      text: '加载中...'
    });
  });
  request.get('/link/getClient', { params: { name: clientQuery.value ,pageNum:dataClient.value.pageNum,pageSize:dataClient.value.pageSize} }).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      dataClient.value.list = res.data.list
      dataClient.value.total = res.data.total
    }
  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    }).finally(() => {
      if (loadingInstance) loadingInstance.close();
    });
}
// 数据回填
const selectClient = (row) => {
  queryForm.clientPartyId = row.comPartyId
  queryForm.clientName = row.partyName
  clientDialogVisible.value = false
}

// 修改
const handleSave = (row) => {
  // 转成绝对值比较
  const act = Math.abs(Number(row.actRebAmt));
  const reb = Math.abs(Number(row.rebAmt));
  // 可补金额不能大于应收金额
  if (act > reb) {
    ElMessage.error('可补金额不能大于应收金额，请重新填写');
    row.actRebAmt = row.rebAmt;
    return;
  }

  request.get('/account/updateAmt', {
    params: {
      id: row.sscOrderLinesLotsId,
      rebAmt: row.actRebAmt
    }
  }).then(res => {
    console.log('res', res);
    if (res.code === 200) {
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('保存失败');
    }
  }).catch(err => {
    console.error(err);
    ElMessage.error('保存异常');
  });
};


// 批量保存
const handleBatchSave = async () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请先选择要确权的数据')
    return
  }

  try {
    for (const row of selectedRows.value) {
      await handleSave(row)  // 等待每次请求完成
    }
    // 所有都执行完毕后再刷新
    await handleQuery()
  } catch (err) {
    console.error(err)
    ElMessage.error('批量确权过程中出现异常')
  }
}



</script>
